package br.net.woodstock.tickettoride.samples.web2;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.net.woodstock.rockframework.utils.ConditionUtils;
import br.net.woodstock.tickettoride.client.TicketData;
import br.net.woodstock.tickettoride.client.TicketHash;
import br.net.woodstock.tickettoride.client.TicketSession;
import br.net.woodstock.tickettoride.client.beans.DefaultTicketHash;
import br.net.woodstock.tickettoride.client.jdk6.TicketSessionHolder;

public class TicketServlet extends HttpServlet {

	private static final long	serialVersionUID	= 1L;

	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		this.doAll(request, response);
	}

	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		this.doAll(request, response);
	}

	@SuppressWarnings("unchecked")
	private void doAll(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Tratando a requisicao");
		String hash = request.getParameter("hash");
		if (ConditionUtils.isNotEmpty(hash)) {
			TicketSession ticketSession = TicketSessionHolder.getInstance().getSession();
			TicketHash th = new DefaultTicketHash(hash);
			TicketData data = ticketSession.getData(th);
			byte[] bytes = data.getBytes();
			request.setAttribute("bytes", bytes);
		} else {
			System.out.println("Sem Hash na URL");
			StringBuilder builder = new StringBuilder();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				System.out.println("Adicionando " + name);
				builder.append(name + "=" + request.getParameter(name) + "\n");
			}
			request.setAttribute("bytes", builder.toString().getBytes());
		}

		request.getRequestDispatcher("/output.jsp").include(request, response);
	}

}
